#include <iostream>
#include <fstream>
#include <string>


using namespace std;

struct beep_record{
	unsigned int size;
	unsigned int offset;
};

int main(int argc, char *argv[])
{
	if (argc < 2){
		cout << " UnpackOldBeeps.exe  [BeepPackageFileName]" << endl;
		return 0;
	}

	ifstream fin(argv[1], ios_base::in | ios_base::binary);
	if (!fin.is_open()){
		cerr << "File open error!" << endl;
		return 1;
	}

	unsigned int beeps_num = 0;
	fin.read(reinterpret_cast<char *>(&beeps_num), sizeof(beeps_num));
	cout << "Beeps number: " << beeps_num << endl;
	beep_record *brs = new beep_record[beeps_num];

	unsigned int count = 0;
	for (count = 0; count < beeps_num; ++count){
		fin.read(reinterpret_cast<char*>(&(brs[count].size)), 4);
		fin.read(reinterpret_cast<char*>(&(brs[count].offset)), 4);
	}

	for (count = 0; count < beeps_num; ++count){
		unsigned int offset_base = 0;
		unsigned int offset = 0;
		unsigned int size = brs[count].size;
		if (0 == count){
			offset_base = 0;
		}
		else {
			offset_base = brs[0].offset;
		}
		//offset = offset_base + brs[count].offset;
		offset = brs[count].offset;
		string fn;
		fn += static_cast<char>(count/10)+'0';
		fn += static_cast<char>(count%10)+'0';
		fn += ".wav";
		cout << "Writing " << fn << endl;
		cout << "Offset " << offset << endl;
		cout << "Size " << size << endl << endl;
		
		ofstream fout(fn.c_str(), ios_base::out | ios_base::binary);
		fin.seekg(offset);
		char *wav = new char[size];
		fin.read(wav, size);
		fout.write(wav, size);
		fout.close();
	}
}
